package Util;

import java.sql.*;

/**
 * @since 2024-06-01
 * @author yooo_fan
 * 数据库工具类
 */
public class JBDCUtil {
    private static Connection openGaussConnection = null;

    private static final String url = "jdbc:postgresql://124.70.107.17:26000/postgres";
    private static final String user = "py_omm";
    private static final String password = "123456@abc";

    // 加载驱动
    static {
        try{
            Class.forName("org.postgresql.Driver");

        } catch (ClassNotFoundException e) {
            System.err.println("驱动加载失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建数据库连接
     */
    public static void getConnect() throws SQLException {
        System.out.println("尝试连接数据库");
        try{
            openGaussConnection = DriverManager.getConnection(url, user, password);
            openGaussConnection.setAutoCommit(false);
            System.out.println("数据库连接成功");

        } catch (SQLException e) {
            System.err.println("数据库连接失败");
            throw new SQLException(e);
        }
    }

    /**
     * 关闭数据库连接
     */
    public static void disConnect(){
        if(openGaussConnection != null)
        {
            try {
                openGaussConnection.close();
            } catch (SQLException e) {
                System.err.println("关闭数据库连接失败");
                throw new RuntimeException(e);
            }
        }
    }
    /**
     * 关闭结果set
     */
    public static void closeResultSet(ResultSet rs){
        if(rs != null)
        {
            try {
                rs.close();
            }catch (SQLException e){
                System.err.println("关机结果集失败");
                throw new RuntimeException();
            }
        }
    }

    /**
     * 检查连接
     * @throws SQLException 数据库错误
     */
    public static void checkConnection() throws SQLException {
        // 检查数据库连接
        if(openGaussConnection == null)
        {
            System.out.println("数据库未连接，重试连接");
            getConnect();
        }
    }

    /**
     * 获取一个预编译状态
     * @param sql SQL语句
     * @return 一个预编译状态
     * @throws SQLException 数据库异常
     */
    public static PreparedStatement getPreparedStatement(String sql) throws SQLException {
        JBDCUtil.checkConnection();
        return openGaussConnection.prepareStatement(sql);
    }

    /**
     * 获取一个返回主键的状态
     * @param sql SQL语句
     * @return 一个预编译状态
     * @throws SQLException 数据库异常
     */
    public static PreparedStatement getPreparedStatementOutputKeys(String sql) throws SQLException {
        JBDCUtil.checkConnection();
        return openGaussConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    }

    /**
     * 提交事务
     * @throws SQLException 数据库异常
     */
    public static void commit() throws SQLException {
        openGaussConnection.commit();
    }
}